#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
"""
import time
import traceback
from _base.base import BasePage
from _step.base import BaseStep
from _step.step import TestCaseList, TestCase
from control.load_variable import LoadVariable
from utils.common import now


class BaseRunner(object):
    def __init__(self, base_page, lv, base_step):
        self.base_page: BasePage = base_page
        self.lv: LoadVariable = lv
        self.base_step: BaseStep = base_step
        self.report_id = base_page.report_id
        self.report_status = 1
        self.completed = 0

    async def batch_run(self, testcase_list: TestCaseList):
        for testcase in testcase_list.children:
            testcase_status = 1
            start_at = time.time()
            start_time = now()
            self.base_page.report_id = self.report_id
            self.base_page.testcase_id = testcase.id
            self.base_page.step_report_list = []
            try:
                await self.base_step.multiple_step(testcase.steps)
                # 导出用例变量到环境变量
                await self.lv.export_var(testcase.config)
            except Exception as e:
                traceback.print_exc()
                testcase_status = 2
                self.report_status = 2
                await self.base_page.log_error(str(e))
            finally:
                await self.send_report(testcase, testcase_status, start_at, start_time)
                self.completed += 1

    async def send_report(self, testcase: TestCase, status, duration_start_time, start_time):
        end_time = now()
        use_time = round((time.time() - duration_start_time) * 1000)
        test_result = {
            "report_id": self.report_id,
            "group_id": testcase.group_id,
            "testcase_id": testcase.id,
            "type": testcase.type,
            "name": testcase.name,
            "tags": testcase.tag,
            # "severity": '',
            "duration": f"{use_time}",
            "status": status,
            "steps": self.base_page.step_report_list,
            "start_time": start_time,
            "end_time": end_time
        }
        # await SendMessage.add_step_debug_data({"data": case_debug_data})
        await self.base_step.add_test_data(test_result)
